const fs = require('fs');
const path = require('path');
const { parse } = require('@vue/compiler-sfc');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;

function memberExpressionToString(node) {
  if (node.type === 'MemberExpression') {
    const objStr = memberExpressionToString(node.object);
    const propStr = node.computed 
      ? `[${memberExpressionToString(node.property)}]` 
      : `.${node.property.name}`;
    return `${objStr}${propStr}`;
  } else if (node.type === 'Identifier') {
    return node.name;
  } else if (node.type === 'StringLiteral') {
    return `'${node.value}'`;
  } else {
    return generate(node).code;
  }
}

const filePath = path.resolve(__dirname, 'App.vue');
const source = fs.readFileSync(filePath, 'utf8');
const { descriptor } = parse(source);

const result = {};

if (descriptor.script) {
  const scriptContent = descriptor.script.content;
  const scriptAst = parser.parse(scriptContent, {
    sourceType: 'module',
    plugins: ['objectRestSpread', 'optionalChaining']
  });

  traverse(scriptAst, {
    ObjectProperty(path) {
      if (path.node.key.name === 'methods') {
        const methodsObj = path.node.value;
        if (methodsObj.type !== 'ObjectExpression') return;

        methodsObj.properties.forEach(method => {
          // 处理不同类型的方法定义
          let methodNode;
          if (method.type === 'ObjectMethod') {
            methodNode = method;
          } else if (method.type === 'ObjectProperty' && method.value) {
            methodNode = method.value;
          } else {
            return;
          }

          // 检查是否为函数类型
          const isFunction = 
            methodNode.type === 'ObjectMethod' ||
            methodNode.type === 'FunctionExpression' ||
            methodNode.type === 'ArrowFunctionExpression';

          if (!isFunction) return;

          const methodName = method.key.name;
          console.log(`正在分析方法: ${methodName}`);

          // 使用 path.traverse 并传递 scope
          traverse(methodNode, {
            CallExpression(callPath) {
              const args = callPath.node.arguments;
              const calleeName = callPath.node.callee.name;
              const firstArg = args[0];
              const thirdArg = args[2];

              if (args.length < 3 || thirdArg?.type !== 'ObjectExpression') return;

              const firstArgStr = firstArg ? memberExpressionToString(firstArg) : '';
              const successProps = thirdArg.properties.filter(prop => 
                ['success', 'sucess'].includes(prop.key.name) && 
                (prop.value.type === 'FunctionExpression' || prop.value.type === 'ArrowFunctionExpression')
              );

              if (successProps.length === 0) {
                result[firstArgStr] = result[firstArgStr] || [];
                // 修复：使用 path.traverse 并传递 scope
                traverse(thirdArg, {
                  CallExpression(innerCallPath) {
                    result[firstArgStr].push(generate(innerCallPath.node).code);
                  }
                }, callPath.scope); // 传递当前作用域
                return;
              }

              successProps.forEach(successProp => {
                const isMisspelled = successProp.key.name === 'sucess';
                const callbackNode = successProp.value;
                
                // 修复：使用 path.traverse 并传递 scope
                traverse(callbackNode, {
                  AssignmentExpression(assignPath) {
                    const assignNode = assignPath.node;
                    if (
                      assignNode.left.type === 'MemberExpression' &&
                      assignNode.left.object.type === 'MemberExpression' &&
                      assignNode.left.object.object.type === 'Identifier' &&
                      assignNode.left.object.object.name === 'that' &&
                      assignNode.left.object.property.name === 'oParams' &&
                      assignNode.left.property.name === 'bEnablePic'
                    ) {
                      const entry = {
                        methodName,
                        functionName: calleeName,
                        line: assignNode.loc.start.line,
                        column: assignNode.loc.start.column,
                        code: generate(assignNode).code,
                        isMisspelled,
                        apiKey: firstArgStr
                      };
                      console.log(`找到匹配项: ${JSON.stringify(entry, null, 2)}`);
                    }
                  },
                  CallExpression(innerCallPath) {
                    // 打印执行的函数调用
                    console.log(firstArgStr, `找到函数调用: ${generate(innerCallPath.node).code}`);
                  }
                }, callPath.scope); // 传递当前作用域
              });
            }
          }, path.scope); // 传递 methods 对象的作用域
        });
      }
    }
  });

  // 处理未找到匹配的情况
  const finalResult = {};
  Object.keys(result).forEach(key => {
    finalResult[key] = Array.from(new Set(result[key]));
  });

  if (Object.keys(finalResult).length > 0) {
    console.log("未找到匹配的赋值语句，以下是success回调中的其他函数调用：");
    console.log(finalResult);
  }
}